package bots;

import model.*;

import java.util.List;

/**
 * @author Alex Vikharev vikharev@yandex-team.ru
 *         created 27.02.12
 */
public class MinMaxClassifierBot extends AbstractBot {
    private final Classifier classifier;

    public MinMaxClassifierBot(String name, Classifier classifier, GameType gameType) {
        super(name, gameType);
        this.classifier = classifier;
    }

    @Override
    public Position setFigure(final Field field, final Figure figure) {
        Position winMove = getWinMove(field, figure);
        if (winMove != null) {
            return winMove;
        }

        List<Position> moves = getPossibleMoves(field, figure);
        double best = Double.POSITIVE_INFINITY;
        Position bestMove = null;

        for (Position move : moves) {
            final Position winMoveEnemy = getWinMove(move.getField(), move.getFigure());
            double max;

            if (winMoveEnemy != null) {
                max = Double.POSITIVE_INFINITY;
            } else {
                max = Double.NEGATIVE_INFINITY;
                List<Position> nextMoves = getPossibleMoves(move.getField(), move.getFigure());
                for (Position nextMove : nextMoves) {
                    double result = classifier.classify(nextMove);
                    if (result > max) {
                        max = result;
                    }
                }
            }

            if (max <= best) {
                best = max;
                bestMove = move;
            }
        }

        return bestMove;
    }
}
